package com.xing.dao.impl;

import com.xing.dao.BookDao;
import com.xing.domain.Book;
import com.xing.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day40web1
 * 2021/4/30 15:21
 */
public class BookDaoImpl implements BookDao {
    private QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());

    @Override
    public List<Book> selectAll() {
        try {
            return qr.query("select * from book", new BeanListHandler<>(Book.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int bookId) {
        try {
            qr.update("delete from book where id=?",bookId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Book selectById(int boolId) {
        try {
            return qr.query("select * from book where id=?", new BeanHandler<>(Book.class),boolId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Book book) {
        Object[] params={book.getTitle(),book.getAuthor(),book.getPublicDate(),book.getPublisher(),book.getIsbn(),book.getPrice(),book.getPicture(),book.getCid(),book.getId()};
        try {
            qr.update("update book set title=?,author=?,publicDate=?,publisher=?,isbn=?,price=?,picture=?,cid=? where id=?",params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(Book book) {
        Object[] params={book.getTitle(),book.getAuthor(),book.getPublicDate(),book.getPublisher(),book.getIsbn(),book.getPrice(),book.getPicture(),book.getCid()};
        try {
            qr.update("insert into book values(null,?,?,?,?,?,?,?,?);",params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
